package com.yanx.system.web.command;

import com.yanx.common.command.Executor;
import com.yanx.common.core.command.VoidCommand;
import com.yanx.common.exception.BusinessException;
import com.yanx.system.base.command.SysDeptCreateCmd;
import com.yanx.system.base.domain.entity.SysDept;
import com.yanx.system.base.domain.manager.SysDeptManager;
import com.yanx.system.base.model.dto.SysDeptDto;
import com.yanx.system.web.infra.constant.UserConstants;
import lombok.AllArgsConstructor;

/**
 * 部门 新增命令
 *
 * @author: gotanks
 * @create: 2023-2-9
 */
@AllArgsConstructor
public class SystemDeptAddCmd extends VoidCommand {
    private SysDeptDto dept;

    @Override
    public void handler(Executor executor) {
        SysDeptManager sysDeptManager = executor.getReceiver(SysDeptManager.class);
        if (sysDeptManager.checkDeptNameUnique(dept.getDeptName(), dept.getParentId())) {
            throw new BusinessException("新增部门'{}'失败，部门名称已存在", dept.getDeptName());
        }

        // 如果父节点不为正常状态,则不允许新增子节点
        SysDept parentDept = sysDeptManager.getById(dept.getParentId());
        if (!UserConstants.DEPT_NORMAL.equals(parentDept.getStatus())) {
            throw new BusinessException("部门停用，不允许新增");
        }
        dept.setAncestors(parentDept.getAncestors() + "," + dept.getParentId());
//        dept.setCreateBy(getUsername());
        executor.execute(new SysDeptCreateCmd(dept));
    }
}